import { Card, Col, Row, Table, Typography } from 'antd';
import { forEach, head, last, toPairs } from 'lodash';
import { memo, useCallback, useEffect, useState } from 'react';

const { Title, Paragraph, Text } = Typography;
const txtEmptyHandle = (txt?: any) => {
  return txt || '-'};
const Storage = () => {
  const [storageList, setStorageList] = useState<Record<string, any>[]>();
  const [storage, setStorage] = useState<StorageEvent>();
  // 获取所有storage
  const getAllStorage = () => {
    const allStorage: Record<string, any>[] = [];

    forEach(
      toPairs(localStorage),
      i => allStorage.push({ key: head(i), value: last(i) })
    );

    setStorageList(allStorage)
  };

  const storageListener = useCallback(() => {
    getAllStorage();
    window.addEventListener('storage', e => {
      setStorage(e);
      getAllStorage();
    }, false);
  }, []);

  useEffect(() => { storageListener(); }, [storageListener]);

  return (
    <Card>
      <Row>
        <Col span={12}>
          <Typography>
            <Title level={5}>变化的Key</Title>
            <Paragraph><Text>{ txtEmptyHandle(storage?.key) }</Text></Paragraph>
            <Title level={5}>之前的 Value</Title>
            <Paragraph><Text>{ txtEmptyHandle(storage?.oldValue) }</Text></Paragraph>
            <Title level={5}>当前的 Value</Title>
            <Paragraph><Text>{ txtEmptyHandle(storage?.newValue) }</Text></Paragraph>
            <Title level={5}>来源</Title>
            <Paragraph><Text>{ txtEmptyHandle(storage?.url) }</Text></Paragraph>
          </Typography>
        </Col>
        <Col span={12}>
          <Table
            columns={[
              { key: 'key', title: 'Key', dataIndex: 'key' },
              { key: 'value', title: 'Value', dataIndex: 'value' },
            ]}
            dataSource={storageList}
          />
        </Col>
      </Row>
    </Card>
  );
};

export default memo(Storage);